package com.pi.push.app.getui.util;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.gexin.rp.sdk.base.IPushResult;
import com.gexin.rp.sdk.base.impl.SingleMessage;
import com.gexin.rp.sdk.base.impl.Target;
import com.gexin.rp.sdk.exceptions.PushSingleException;
import com.gexin.rp.sdk.http.IGtPush;
import com.gexin.rp.sdk.template.TransmissionTemplate;
import com.pi.base.dto.result.ServiceResult;
import com.pi.config.model.PartnerPushConfig;
import com.pi.push.app.dto.PushInfo;
import com.pi.push.app.getui.factory.GtTemplateFactory;
import com.pi.push.dto.result.respcode.AppPushResp;

/** 
* @author chenmfa
* @version 创建时间：2017年3月29日 下午4:52:01 
* @description
*/
public class PushBase {
  private static Logger logger = LoggerFactory.getLogger(PushBase.class);
  private PushInfo pushInfo;
  
  public PushBase(PushInfo pushInfo){
    this.pushInfo = pushInfo;
  }
  
  public ServiceResult<String> push(){
    String msgTag = "";
    IPushResult result = null;
    IGtPush push = null;
    SingleMessage singleMessage = null;
    Target target= null;
    try {
      msgTag= "["+pushInfo.getMsgTag()+"][GT-"+pushInfo.getDeviceType()+"]";
      String channel = pushInfo.getPushChannel();
      if(StringUtils.isBlank(channel)){
        logger.error(msgTag+"本次推送CID为空,所有参数为："+JSON.toJSONString(pushInfo));
        return ServiceResult.newFailResult(
            AppPushResp.RESP_CLIENT_ID_EMPTY.getTag(), AppPushResp.RESP_CLIENT_ID_EMPTY.getErrorCode());
      }
      PartnerPushConfig config = pushInfo.getPushConfig();
      if(null == config){
        logger.error("未获取到OEM推送信息,不推送");
        return ServiceResult.newFailResult(
            AppPushResp.RESP_PUSH_CONFIG_EMPTY.getTag(), AppPushResp.RESP_PUSH_CONFIG_EMPTY.getErrorCode());
      }
    	logger.info("使用的配置信息:{}", JSON.toJSONString(config));
      //useSSL表明是使用ssl传输还是普通http传输
      push = new IGtPush(config.getAppKey(),
          config.getMasterSecret(), false);
      // host为域名。根据host来区分是http还是https
      // IGtPush push = new IGtPush(host, appkey, master);
      TransmissionTemplate template = GtTemplateFactory.getTransmissionTemplate(pushInfo, msgTag);
      
      singleMessage = new SingleMessage();
      singleMessage.setOffline(true);
      //设置消息有效时间为1个小时,微秒
      singleMessage.setOfflineExpireTime(3600*1000*24);
      singleMessage.setData(template);
      //设置推送的网络，1为WIFI环境下，0为不限制网络
      singleMessage.setPushNetWorkType(0);
      target = new Target();
      target.setAppId(config.getAppId());
      //暂时写死，后期改成baiduchannelID
      //target.setClientId(Constants.gtCid);
      target.setClientId(channel);
      //用户别名和cid只能任选一个来推送
      //target.setAlias(alias);
      result = push.pushMessageToSingle(singleMessage, target);
      if("AppidError".equalsIgnoreCase((null !=result)?result.getResponse().toString():"")){
        logger.error("推送错误，AppId:%s,版本:%s,合作商：%s",
            config.getAppId());
        return ServiceResult.newFailResult(
            AppPushResp.RESP_PUSH_FAIL.getTag(), AppPushResp.RESP_PUSH_FAIL.getErrorCode());
      }
      logger.info(msgTag+((null !=result)?result.getResponse().toString():""));
      return ServiceResult.OK;
    } catch (PushSingleException e) {
      logger.error(msgTag,e);
      try {
        result = push.pushMessageToSingle(singleMessage, target, e.getRequestId());
        return ServiceResult.OK;
      } catch (PushSingleException e1) {
        logger.error(msgTag,e1);
        return ServiceResult.newFailResult(
            AppPushResp.RESP_UNKNOW_ERROR.getTag(), AppPushResp.RESP_UNKNOW_ERROR.getErrorCode());
      }
    } catch (Exception e){
      logger.error(msgTag,e);
      return ServiceResult.newFailResult(
          AppPushResp.RESP_UNKNOW_ERROR.getTag(), AppPushResp.RESP_UNKNOW_ERROR.getErrorCode());
    } 
  }
}
